<?php

namespace app\beautiful\logic\printer;

use app\common\helper\printer\feie\FeiePrinter;

use app\common\helper\printer\Yly\YlyPrinter;

use app\common\model\ShopModel;

use app\beautiful\model\PrinterModel;

use app\beautiful\model\setting\PrinterAppModel;



class PrinterLogic {

    protected $shopId;

    protected $shop;

    protected $setting;

    public function __construct($shopId)

    {

       try{

           if(null === $shop = ShopModel::find($shopId)) $this->error('商铺不存在');

           $this->shopId=$shopId;

           $this->shop=$shop;



           //判断配置

           if(null === $setting = PrinterAppModel::where([

                   ['shop_id','=',$shopId],

                   ['is_delete','=',0]

               ])->find()){

               $this->error('未配置设置');

           }

           $this->setting=$setting->toArray();

       } catch (\Exception $e){



       }

    }



    public function print($type,$id,$produce_printer_ids=[])

    {



        try{

            $printers=$this->getPrinterList($type,$produce_printer_ids);

            foreach ($printers as $printer){

                if($printer->app_type=='yly'){

                    $ContentLogic=new PrinterYlyContentLogic();

                    $content=$ContentLogic->$type($this->shop,$id,0,$printer['size']);

                    $YlyPrinter=new YlyPrinter($this->setting);

                    for ($i=0;$i<$printer->print_num;$i++){

                        $YlyPrinter->printMsg($printer->machine_code,$content);
                    }

                }else{

                    $FeiePrinter = new FeiePrinter($this->setting);

                    $ContentLogic=new PrinterFeieContentLogic();

                    $content=$ContentLogic->$type($this->shop,$id);

                    $FeiePrinter->printMsg($printer->print_sn,$content);

                }

            }

        }catch (\Exception $e){

            wyuLog('printer.txt',$e->getMessage());

        }

        return true;

    }



    protected function getPrinterList($type,$produce_printer_ids=[])

    {

        $printers=PrinterModel::where([

            ['shop_id','=',$this->shopId],

        ])->whereRaw(" FIND_IN_SET('{$type}',jurisdiction)")

            ->whereNotIn('printer_id',$produce_printer_ids)

            ->select();

        return $printers;

    }



    public function error($message){

        throw new \Exception($message);

    }

}

